package com.itheima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.exception.CustomException;
import com.itheima.filter.LoginFilter;
import com.itheima.mapper.UserDao;
import com.itheima.pojo.User;
import com.itheima.result.R;
import com.itheima.service.UserService;
import com.itheima.util.SMSUtils;
import com.itheima.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 斌
 * @DateTime: 2023年02月10日  19:20:01
 * @Description: com.itheima.service.Impl
 * @Version: 1.0
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Override
    public R sendMsg(User user, HttpSession session) {
        log.info("发送验证码的手机号:{}",user.getPhone());
        //从工具类中获取随机生成的验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        log.info("生成的验证码:{}",code);
        //调用短信模板，验证码传入
        //SMSUtils.sendMessage("阿里云短信测试","SMS_154950909","18089734027",Integer.toString(code));
        //将phone为key，验证码为value，存入session
        //session.setAttribute(user.getPhone(),Integer.toString(code));


        //优化1：将验证码存入Redis中，解决无法获取session的情况，比如手机和电脑两者不一样，要设置过期时间，因为是验证码登录的
        redisTemplate.opsForValue().set(user.getPhone(),Integer.toString(code),1L, TimeUnit.MINUTES);
        //返回结果
        return R.success("验证码发送成功");
    }

    @Override
    public R login(User user, HttpSession session) {
        //查询数据库是否有该用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,user.getPhone());
        User queryUser = userDao.selectOne(wrapper);
        //判断
        //没有，直接进行添加
        if (queryUser == null){
            int insertResult = userDao.insert(user);
            if (insertResult <= 0 ){
                throw new CustomException("数据异常，请稍后重试");
            }
        }
        log.info("session信息:{}",session.toString());
        //从session中获取之前存的验证码，和用户发过来的验证码进行比较
        //String code = (String) session.getAttribute(user.getPhone());


        //从Redis中取之前存的验证码
        String code = (String) redisTemplate.opsForValue().get(user.getPhone());


        assert code != null;
        if (code.equals(user.getCode())){
            //将用户id存入session中，为了过滤登陆请求
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,user.getPhone());
            User selectUser = userDao.selectOne(queryWrapper);
            session.setAttribute("user",selectUser.getId());

            //验证码取完之后立即删除，防止恶意攻击,error的话，让用户重试，因为设置了过期时间，但是成功后应立即删除
            redisTemplate.delete(user.getPhone());

            //返回登录结果
            return R.success("登录成功");
        }




        return R.error("验证码或手机号有误");
    }

    @Override
    public R loginOut( HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
